/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2016 abel533@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package tk.mybatis.springboot.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.springboot.cons.AppCons;
import tk.mybatis.springboot.model.TActivity;
import tk.mybatis.springboot.model.TJoiners;
import tk.mybatis.springboot.model.TUser;
import tk.mybatis.springboot.service.ActivityJoinerService;
import tk.mybatis.springboot.service.ActivityService;
import tk.mybatis.springboot.service.UserService;
import tk.mybatis.springboot.util.DateUtils;
import tk.mybatis.springboot.util.GroupUtils;
import tk.mybatis.springboot.util.RedisUtil;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/activity")
public class ActivityController extends BaseController {
    Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ActivityJoinerService activityJoinerService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping(value = "/index")
    public ModelAndView indexPage() {
        log.info("indexPage()...");
        ModelAndView modelAndView = new ModelAndView("activity/index");
        TActivity activity = new TActivity();
        activity.setIscurrent(0);
        TActivity currentActivity = activityService.getTActivity(activity);
        if (currentActivity != null) {
            modelAndView.addObject("activity", currentActivity);
            if (currentActivity.getStatus().equals("2") || currentActivity.getStatus().equals("3")) {
                ArrayList<ArrayList<TJoiners>> group = JSONObject.parseObject(currentActivity.getResultlist(), ArrayList.class);
                modelAndView.addObject("groupResult", group);
            }
            if (currentActivity.getStatus().equals("3")) {
                modelAndView.addObject("lucknum", currentActivity.getLucker());
            }
        }
        return modelAndView;
    }

    @RequestMapping(value = "/activityCreatePage")
    public ModelAndView activityCreatePage(TActivity tactivity) {
        log.info("activityCreatePage()...");
        ModelAndView modelAndView = new ModelAndView("activity/activity_create");
        TActivity activity = new TActivity();
        activity.setIscurrent(0);
        TActivity currentActivity = activityService.getTActivity(activity);
        if (currentActivity != null) {
            modelAndView.addObject("hasActivity", true);
            log.info("当前活动已经被创建，需结束当前活动才能创建新活动");
        }
        return modelAndView;
    }

    @RequestMapping(value = "/createActivity")
    public String createActivity(TActivity tactivity) {
        log.info("createActivity()...");
        if (TextUtils.isEmpty(tactivity.getStartTime())) {
            tactivity.setStartTime(DateUtils.getNowTime());
        }
        log.info("活动开始时间：{}", tactivity.getStartTime());
        TActivity activity = new TActivity();
        activity.setPeriod(DateUtils.getYMD(DateUtils.parse(tactivity.getStartTime())));
        activity.setStatus("0");
        activity.setIscurrent(0);
        activity.setStartTime(tactivity.getStartTime());
        try {
            activityService.save(activity);
            log.info("活动创建成功");
            redisUtil.set(AppCons.REDIS_KEY_STARTTIME, DateUtils.dateToUnixTimestamp(tactivity.getStartTime()));
            redisUtil.set(AppCons.REDIS_KEY_STATUSCHANGED, false);
            return "true";
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }


    }

    @RequestMapping(value = "/getCurrentActivity")
    public TActivity getCurrentActivity() {
        log.info("getCurrentActivity()...");
        TActivity activity = new TActivity();
        activity.setIscurrent(0);
        TActivity tActivity = activityService.getTActivity(activity);
        if (tActivity != null) {
            log.info("活动获取成功");
        } else {
            log.info("活动获取失败");
        }
        return tActivity;
    }

    /**
     * 设置活动开始时间
     *
     * @param activity
     */
    @RequestMapping(value = "/setActivityTime")
    public void setActivityTime(TActivity activity) {
        log.info("setActivityTime()...");
        log.info("设置活动开始时间：" + activity.getStartTime());
        activityService.save(activity);
    }


    /**
     * 获取当前活动参与用户
     */
    @RequestMapping(value = "/getCurrentActivityJoiners")
    public JSONObject getCurrentActivityJoiners() throws Exception {
        log.info("getCurrentActivityJoiners()...");
        JSONObject jsonObject = new JSONObject();
        TActivity activity = getCurrentActivity();
        if (activity == null) {
            return getFaildResponse(jsonObject, "活动尚未创建，无法参与！");
        }
        TJoiners tJoiners = new TJoiners();
        tJoiners.setActivityId(activity.getId());
        List<TJoiners> joiners = activityJoinerService.getAll(tJoiners);
        jsonObject.put("joiners", joiners);
        log.info("datas{}", JSONObject.toJSONString(joiners));
        return getSuccessResponse(jsonObject);
    }

    /**
     * 活动分组
     */
    @RequestMapping(value = "/groupJoiners")
    public ModelAndView groupJoiners(int groupNum) throws Exception {
        log.info("groupJoiners()...");
        ModelAndView modelAndView = new ModelAndView("activity/index");
        log.info("开始进行分组。。。");
        log.info("组数：{}",groupNum);
        JSONObject jsonObject = new JSONObject();
        TActivity activity = getCurrentActivity();
        if (activity == null) {
            modelAndView.addObject("error", "活动尚未创建，禁止操作！");
            return modelAndView;
        }
        if (activity.getStatus().equals("1")) {
            TJoiners tJoiners = new TJoiners();
            tJoiners.setActivityId(activity.getId());
            List<TJoiners> joiners = activityJoinerService.getAll(tJoiners);
            if (joiners.size() > 10) {
                ArrayList<ArrayList<TJoiners>> group = GroupUtils.group(groupNum, joiners);
                jsonObject.put("datas", group);
                activity.setStatus("2");
                activity.setResultlist(JSONObject.toJSONString(group));
                activityService.save(activity);
                modelAndView.addObject("groupResult", group);
                log.info("分组成功，活动参与截止");
            } else {
                log.info("参与者过少，不能分组,需大于10人！");
                modelAndView.addObject("error", "参与者过少，不能分组,需大于10人！");
            }

        }
        modelAndView.addObject("activity", activity);
        return modelAndView;
    }

    /**
     * 抽奖
     */
    @RequestMapping(value = "/sharklucker")
    public ModelAndView sharkLucker() throws Exception {
        log.info("sharkLucker()...");
        ModelAndView modelAndView = new ModelAndView("activity/index");
        log.info("开始进行抽奖。。。");
        JSONObject jsonObject = new JSONObject();
        TActivity activity = getCurrentActivity();
        if (activity == null) {
            modelAndView.addObject("error", "活动尚未创建，禁止操作！");
            return modelAndView;
        }
        if (activity.getStatus().equals("2")) {
            ArrayList<ArrayList<TJoiners>> group = JSONObject.parseObject(activity.getResultlist(), ArrayList.class);
            int lucker = new Random().nextInt(group.size());
            activity.setStatus("3");
            activity.setLucker(lucker);
            activityService.save(activity);
            modelAndView.addObject("groupResult", group);
            modelAndView.addObject("lucknum", lucker);
            log.info("lucker:{}", lucker);
            log.info("抽奖成功，活动结束!");
        } else {
            modelAndView.addObject("error", "该操作无法执行！");
        }
        modelAndView.addObject("activity", activity);
        return modelAndView;
    }

    /**
     * 结束活动
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/overActivity")
    public ModelAndView overActivity() throws Exception {
        log.info("overActivity()...");
        ModelAndView modelAndView = new ModelAndView("activity/index");
        log.info("活动结束。。。");
        JSONObject jsonObject = new JSONObject();
        TActivity activity = getCurrentActivity();
        if (activity == null) {
            modelAndView.addObject("error", "活动尚未创建，禁止操作！");
            return modelAndView;
        }
        activity.setIscurrent(1);
        activity.setEndTime(DateUtils.getNowTime());
        activityService.save(activity);
        return modelAndView;
    }

    @RequestMapping(value = "/activitylist")
    public ModelAndView activityList(TActivity activity) {
        ModelAndView modelAndView = new ModelAndView("activity/activitylist");
        activity.setIscurrent(1);
        activity.setStatus("3");
        List<TActivity> datas = activityService.getAll(activity);
        Collections.reverse(datas);
        for (TActivity tActivity : datas) {
            StringBuilder sb = new StringBuilder();
            ArrayList<JSONArray> group = JSONObject.parseObject(tActivity.getResultlist(), ArrayList.class);
            JSONArray joiners = group.get(tActivity.getLucker());
            Iterator<Object> it = joiners.iterator();
            while (it.hasNext()) {
                JSONObject tJoiners = (JSONObject) it.next();
                sb.append(tJoiners.get("realname"));
                sb.append("、");
            }
            sb.deleteCharAt(sb.length() - 1);
            tActivity.setResultlist(sb.toString());
        }
        modelAndView.addObject("datas", datas);
        log.info("datas{}", JSONObject.toJSONString(datas));
        return modelAndView;
    }

}
